package cn.anecansaitin.firecrafting.common.crafting;

import cn.anecansaitin.firecrafting.ModConstant;
import cn.anecansaitin.firecrafting.api.client.crafting.IJEIRecipeRender;
import cn.anecansaitin.firecrafting.client.crafting.FireEntityRecipeRender;
import cn.anecansaitin.firecrafting.common.Config;
import cn.anecansaitin.firecrafting.common.util.ModJsonReader;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobSpawnType;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistryEntry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

//生成实体配方
public class FireEntityRecipe extends SimpleFireRecipe {
    private final ImmutableList<EntityType<?>> outputs;

    public FireEntityRecipe(ResourceLocation id, ImmutableList<Block> fireBlock, NonNullList<Ingredient> inputs, ImmutableList<EntityType<?>> outputs) {
        super(id, fireBlock, inputs);
        this.outputs = outputs;
    }

    @Override
    public IJEIRecipeRender getRender() {
        return FireEntityRecipeRender.INSTANCE;
    }

    public List<EntityType<?>> getOutputs() {
        return outputs;
    }

    //在配方正确时进行一系列行为
    @Override
    public boolean doAction(List<ItemStack> stacks, BlockPos pos, Level world) {
        //进行配方检测
        if (match(stacks, pos, world)) {
            //遍历生成产物
            outputs.forEach(e -> {
                //生成实体对象
                Entity spawn = e.spawn((ServerLevel) world, null, null, pos, MobSpawnType.COMMAND, true, false);
                if (spawn != null) {
                    //将实体的火焰时间设置为负数（另起能在一段时间内免疫火焰伤害）
                    spawn.setRemainingFireTicks(-Config.WORLD_MAX_FIRE_PROTECTION.get());
                }
            });
            return true;
        }
        return false;
    }

    //返回配方指定的序列化器
    @Override
    public @NotNull RecipeSerializer<?> getSerializer() {
        return ModRecipeTypes.FIRE_ENTITY_SERIALIZER.get();
    }

    //序列化器实现类
    public static class Serializer extends ForgeRegistryEntry<RecipeSerializer<?>> implements RecipeSerializer<FireEntityRecipe> {
        public static final String NAME = ModConstant.MOD_ID + ":fire_entity_crafting";

        //从json转为配方
        @Override
        public @NotNull FireEntityRecipe fromJson(@NotNull ResourceLocation id, @NotNull JsonObject json) {
            //获取配方物品成分
            NonNullList<Ingredient> nonnulllist = ModJsonReader.ingredientsFromJson(GsonHelper.getAsJsonArray(json, "ingredients"));
            //判断配方成分的可用性
            if (nonnulllist.isEmpty()) {
                throw new JsonParseException("火焰燃烧(实体)配方内没有任何原料 No ingredients for fire entity recipe");
            } else if (nonnulllist.size() > Config.WORLD_MAX_COUNT.get()) {
                throw new JsonParseException("火焰燃烧(实体)配方内的原料超出上限" + Config.WORLD_MAX_COUNT.get() + "  Too many ingredients for fire entity recipe. The maximum is " + Config.WORLD_MAX_COUNT.get());
            }
            //获取配方实体产物
            ImmutableList<EntityType<?>> outputs = ImmutableList.copyOf(ModJsonReader.entityTypesFromJson(json, "output"));
            if (outputs.isEmpty()) {
                throw new JsonParseException("火焰燃烧(实体)配方内没有任何产物 No output for fire entity recipe");
            }
            //获取可用火焰
            ImmutableList<Block> fire = ImmutableList.copyOf(ModJsonReader.blocksFromJson(json, "fire"));
            //判断火焰可用性
            if (fire.isEmpty()) {
                throw new JsonParseException("火焰燃烧(实体)配方内没有指定火焰 No fire block for fire entity recipe");
            }

            return new FireEntityRecipe(id, fire, nonnulllist, outputs);
        }

        //通过网络获取配方
        @Nullable
        @Override
        public FireEntityRecipe fromNetwork(@NotNull ResourceLocation id, @NotNull FriendlyByteBuf buffer) {
            //从buffer读取火焰数量
            int fireCount = buffer.readVarInt();
            //新建构建器
            ImmutableList.Builder<Block> fireBuilder = ImmutableList.builder();
            //循环读取火焰
            for (int i = 0; i < fireCount; i++) {
                fireBuilder.add(ForgeRegistries.BLOCKS.getValue(buffer.readResourceLocation()));
            }
            //从buffer读取实体数量
            int entityCount = buffer.readVarInt();
            //新建实体集合构建器
            ImmutableList.Builder<EntityType<?>> entityBuilder = ImmutableList.builder();
            //循环读取实体
            for (int i = 0; i < entityCount; i++) {
                entityBuilder.add(ForgeRegistries.ENTITIES.getValue(buffer.readResourceLocation()));
            }
            //从buffer中获取配方成分数量并创建集合
            NonNullList<Ingredient> input = NonNullList.withSize(buffer.readVarInt(), Ingredient.EMPTY);
            //从buffer中获取指定数量成分
            for (int i = 0; i < input.size(); i++) {
                input.set(i, Ingredient.fromNetwork(buffer));
            }
            return new FireEntityRecipe(id, fireBuilder.build(), input, entityBuilder.build());
        }

        //将配方发送到网络
        @Override
        public void toNetwork(@NotNull FriendlyByteBuf buffer, @NotNull FireEntityRecipe recipe) {
            //获取配方火焰
            ImmutableList<Block> fireBlock = recipe.fireBlock;
            //向buffer写入火焰数量
            buffer.writeVarInt(fireBlock.size());
            //遍历写入火焰
            fireBlock.forEach((b) -> buffer.writeResourceLocation(b.getRegistryName()));
            //获取配方实体产物
            ImmutableList<EntityType<?>> outputs = recipe.outputs;
            //向buffer写入实体数量
            buffer.writeVarInt(outputs.size());
            //遍历写入实体
            outputs.forEach((e) -> buffer.writeResourceLocation(e.getRegistryName()));
            //获取配方成分
            NonNullList<Ingredient> inputs = recipe.inputs;
            //向buffer写入成分数量
            buffer.writeVarInt(inputs.size());
            //遍历写入成分
            inputs.forEach((i) -> i.toNetwork(buffer));
        }
    }
}